/**
 * @Description: axios网络请求
 * @author zhaojiuyi
 * @date 2023/4/13
 */
import axios, {AxiosInstance, AxiosRequestConfig, AxiosResponse} from "axios";
import {responseInterceptor} from "./interceptor/response.interceptor";
import {requestInterceptor} from "./interceptor/request.interceptor";
import {ApiResponse,} from "./types";

// export const source = axios.CancelToken.source()

export class HttpRequest {
    instance: AxiosInstance

    constructor(config: AxiosRequestConfig) {
        this.instance = axios.create(config)
        /* 全局请求拦截器 */
        this.instance.interceptors.request.use(requestInterceptor)
        /* 全局响应拦截器 */
        this.instance.interceptors.response.use(responseInterceptor)
    }

    request = <U>(config: AxiosRequestConfig | string, method: string = "GET"): Promise<ApiResponse<U>> => {
        // config.cancelToken = source.token
        if (typeof config === "string") {
            config = {url: config}
        }
        config.method = config.method ? config.method : method
        return new Promise((resolve, reject) => {
            this.instance.request(config as AxiosRequestConfig)
                .then((response: AxiosResponse<ApiResponse<U>>) => {
                    resolve(response.data)
                }).catch(error => {
                reject(error)
            })
        })
    }

    get = <U>(config: AxiosRequestConfig | string): Promise<ApiResponse<U>> => {
        return this.request<U>(config, "GET")
    }

    post = <U>(config: AxiosRequestConfig | string): Promise<ApiResponse<U>> => {
        return this.request<U>(config, "POST")
    }

    put = <U>(config: AxiosRequestConfig | string): Promise<ApiResponse<U>> => {
        return this.request<U>(config, "PUT")
    }

    delete = <U>(config: AxiosRequestConfig | string): Promise<ApiResponse<U>> => {
        return this.request<U>(config, "DELETE")
    }
}
